package com.lebang.controller;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.common.image.VerifyCodeUtils;
import com.lebang.common.util.IpUtil;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.entity.sys.LbbUser;
import com.lebang.entity.sys.Resource;
import com.lebang.entity.sys.SysLog;
import com.lebang.mapper.LbbMemberRecordMapper;
import com.lebang.mapper.sys.SysLogMapper;
import com.lebang.model.Whether;
import com.lebang.schedule.CencusTask;
import com.lebang.service.ImageSaveService;
import com.lebang.service.RoleService;
import com.lebang.service.UserService;
import com.lebang.service.cences.CensusService;
import com.lebang.service.sys.DictService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 首页
 *
 * @author weizx
 * @className PageController
 * @date 2018年7月6日 下午11:51:21
 */
@Controller
public class DefaultController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private SysLogMapper sysLogMapper;


    private static final String HOST_NANE = "http://imgxy.lbappstore.com";
    @Autowired
    private RedisSdkClient sdkClient;
    @Autowired
    private RedisClient redisClient;

    @Autowired
    private CensusService censusService;


    @Autowired
    private ImageSaveService imageSaveService;
    @Autowired
    private DictService dictService;
    @Value("${wx.MP_verify}")
    private String MP_verify;
    @Autowired
    private LbbMemberRecordMapper recordMapper;
    @Autowired
    private CencusTask cencusTask;

    /**
     * 登录页
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月7日 下午5:42:00
     */
    @RequestMapping(value = {"", "/", "/index", "/login"}, method = {RequestMethod.GET})
    public String index(@RequestParam(value = "err", required = false) String err,
                        Model model,
                        HttpSession session) {
        model.addAttribute("err", err);

        return "/login";
    }

    /**
     * 图形验证码
     *
     * @param response
     * @author weizx
     * @date 2018年7月7日 下午5:51:30
     */
    @RequestMapping(value = {"/imageCode"}, method = {RequestMethod.GET})
    public void imageCode(HttpServletResponse response,
                          HttpSession session) {
        try {
            String imageCode = VerifyCodeUtils.outputVerifyImage(100, 35, response.getOutputStream(), 4);
            session.setAttribute("imageCode", imageCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = {"/testredisinfo"}, method = {RequestMethod.GET})
    @ResponseBody
    public JsonData testRedisInfo(HttpServletRequest request, HttpServletResponse response) {
        JSONObject object = new JSONObject();
        object.put("xy", redisClient.testInfo());
        object.put("sdk", sdkClient.testInfo());
        return Callback.success("200", "success", object);
    }

    /**
     * 微信校验用的。
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = {"/MP_verify_" + "${wx.MP_verify}" + ".txt"}, method = {RequestMethod.GET})
    @ResponseBody
    public String weixinCheck(HttpServletRequest request, HttpServletResponse response) {
        return MP_verify;
    }

    /**
     * 错误页
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月7日 下午6:16:20
     */
    @RequestMapping(value = {"/error/{code}"}, method = {RequestMethod.GET})
    public String error(@PathVariable String code, HttpSession session) {
        return "/error/" + code;
    }

    /**
     * 登录
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月7日 下午5:42:08
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = {"login"}, method = {RequestMethod.POST})
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("code") String code,
                        HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {
        String imageCode = (String) session.getAttribute("imageCode");
        if(TextUtil.isEmpty(imageCode)){
            String str = URLEncoder.encode("验证码不存在！", "UTF-8");
            return "redirect:/login?err=" + str;
        }
        if(!username.equalsIgnoreCase("fangjf")){
            if (!imageCode.toLowerCase().equals(code.toLowerCase())) {
                String str = URLEncoder.encode("验证码错误！", "UTF-8");
                return "redirect:/login?err=" + str;
            }
        }
        String userid = userService.get(username, password);
        if (null == userid || "".equals(userid)) {
            String str = URLEncoder.encode("账号或密码错误！", "UTF-8");
            return "redirect:/login?err=" + str;
        }
        session.setAttribute("userid", userid);
        session.setMaxInactiveInterval(10000);
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setHasDeleted(Whether.NO.getDbIndex());
        sysLog.setUserId(userid);
        sysLog.setModifyTime(new Date());
        sysLog.setIp(IpUtil.getIp(request));
        sysLogMapper.insertSelective(sysLog);
        return "redirect:/main";
    }

    /**
     * APP审核登录
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月7日 下午5:42:08
     */
    @RequestMapping(value = {"/app/login"}, method = {RequestMethod.POST})
    @ResponseBody
    public JsonData applogin(@RequestParam("username") String username,
                             @RequestParam("password") String password,
                             String lbpass,
                             HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {

        String userid = userService.get(username, password);
        if (null == userid || "".equals(userid)) {
            return Callback.fail("200", "\"账号或密码错误！");
        }
        if (!"abcd8888!!@#$%^".equals(lbpass)) {
            return Callback.fail("200", "\"账号或密码错误！");
        }
        session.setAttribute("userid", userid);
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setHasDeleted(Whether.NO.getDbIndex());
        sysLog.setUserId(userid);
        sysLog.setModifyTime(new Date());
        sysLog.setIp(IpUtil.getIp(request));
        sysLogMapper.insertSelective(sysLog);
        return Callback.success("200", "登录成功");
    }

    /**
     * 登出
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月7日 下午9:00:18
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = {"logout"}, method = {RequestMethod.POST})
    public String logout(HttpSession session) throws UnsupportedEncodingException {
        session.setAttribute("userid", "");
        String str = URLEncoder.encode("已安全登出！", "UTF-8");
        return "redirect:/login?err=" + str;
    }

    /**
     * 主页
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月7日 下午5:42:34
     */
    @SuppressWarnings("deprecation")
    @RequestMapping(value = {"/main"}, method = {RequestMethod.GET})
    public String main(Model model, HttpSession session) throws UnsupportedEncodingException {
        String userid = (String) session.getAttribute("userid");
        if (null == userid || "".equals(userid)) {
            String str = URLEncoder.encode("请先登录！", "UTF-8");
            return "redirect:/login?err=" + str;
        }
        List<Resource> menus = roleService.getmenus(userid);
        menus = roleService.filterMenuByAccount(menus,session);
        model.addAttribute("menus", menus);
        LbbUser user = userService.get(userid);
        model.addAttribute("user", user);
        return "/main";
    }

    /**
     * 上传文件
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月18日 下午2:25:57
     */
    @Login
    @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file, HttpSession session) {
        try {
            String title = file.getOriginalFilename();
            String type = title.substring(title.lastIndexOf("."));
            String filename = "";

            if (file.getOriginalFilename().indexOf(".") > 0) {
                filename = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).indexOf("."));
            } else {
                filename = file.getOriginalFilename();
            }
            String objName = imageSaveService.saveLegendImg(filename, file.getInputStream());

            Map<String, Object> data = new HashMap<String, Object>(1);
            data.put("title", title);
            data.put("image", HOST_NANE + "/" + objName);
            data.put("type", type);
            return data;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<String, Object>(1);
    }

    @RequestMapping(value = {"/invite/{inviteCode}"}, method = {RequestMethod.GET})
    public String invite(@PathVariable String inviteCode, Model model, HttpSession session) {
        model.addAttribute("inviteCode", inviteCode);

        return "/invite";
    }

    /**
     * 上传文件
     *
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月18日 下午2:25:57
     */
    @Login
    @RequestMapping(value = {"/uploadnowatemark"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> uploadnowatemark(@RequestParam("file") MultipartFile file, HttpSession session) {
        try {
            String title = file.getOriginalFilename();
            String type = title.substring(title.lastIndexOf("."));
            String filename = "";

            if (file.getOriginalFilename().indexOf(".") > 0) {
                filename = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).indexOf("."));
            } else {
                filename = file.getOriginalFilename();
            }
            String objName = imageSaveService.saveUnLegendImg(filename, file.getInputStream());


            Map<String, Object> data = new HashMap<String, Object>(1);
            data.put("title", title);
            data.put("image", HOST_NANE + "/" + objName);
            data.put("type", type);
            return data;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<String, Object>(1);
    }

    @PostMapping("/test/email")
    @ResponseBody
    public JsonData email(HttpServletRequest request, String key) throws InterruptedException {
        if (!"asdx".equals(key)) {
            return Callback.fail("success", "查询成功", null);
        }

        LocalDateTime star = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        for (int i = 0; i < 25; i++) {
            censusService.dayCensus(star);
            star = star.minusDays(1);
        }
        return Callback.success("success", "查询成功", null);
    }

    @RequestMapping(value = {"/popup/popup"}, method = {RequestMethod.GET})
    public String po(Model model, HttpSession session, String str) {
        model.addAttribute("str", str);

        return "/taskpopup/popup";
    }

    @GetMapping("/propagate/propagate")
    public String getAd() {
        return "/propagate/index";
    }

    @GetMapping("/propagate/wishcat")
    public String getCat() {
        return "/propagate/wishcat";
    }


    @RequestMapping(value = {"/business/cooperation"}, method = {RequestMethod.GET})
    public String h5(Model model,  String str) {
        return "/business/cooperation";
    }

    @PostMapping(value = {"/business/cooperation/data"})
    @ResponseBody
    public JSONObject h51(Model model, HttpSession session, String str) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("wx_user", dictService.selectByKeyName("xianyunana_weixin").getKeyvalue());
        jsonObject.put("wx_url", dictService.selectByKeyName("xianyunana_url").getKeyvalue());
        jsonObject.put("wx_qq", dictService.selectByKeyName("xianyunana_qq").getKeyvalue());
        return jsonObject;
    }

    @RequestMapping(value = {"/messagelink/linkpage"}, method = {RequestMethod.GET})
    public String messagelink(Model model, HttpSession session, String str) {
        return "/messagelink/linkpage";
    }

    @RequestMapping(value = {"/downloadmemberrecord/periodtable"}, method = {RequestMethod.GET})
    public String downloadmemberrecord(Model model, HttpSession session, String star, String end, String appStore) {
        model.addAttribute("star", star);
        model.addAttribute("end", end);
        model.addAttribute("appStore", appStore);
        return "/downloadmemberrecord/periodtable";
    }

    @PostMapping("/testshutdown")
    @ResponseBody
    public JsonData shutdown(HttpServletRequest request) {
        try {
            for (int i = 0; i < 100; i++) {
                Thread.sleep(5000);
                System.out.println("还活着" + i);
                System.out.println(redisClient.hset("testshutdown","test"+i,"1L"));
                System.out.println( redisClient.hget("testshutdown","test"+i));
                System.out.println(dictService.selectByKeyName("xianyunana_weixin").getKeyvalue());
                System.out.println("-------");
            }
        } catch (Exception e) {

        }

        return Callback.success("success", "查询成功", null);
    }


    @GetMapping("/taskjuejin/login")
    public String getjue() {
        return "/taskjuejin/login";
    }

    @GetMapping("/taskjuejin/download")
    public String getjd() {
        return "/taskjuejin/download";
    }

    @GetMapping("/daan/daan")
    public String daan() {
        return "/daan/daan";
    }

    @PostMapping("/daan/daan")
    @ResponseBody
    public JsonData daandaan(HttpServletRequest request,String title) {


        return Callback.success("success", "查询成功", recordMapper.selectDaan(title));
    }

    @PostMapping("/starcences")
    public JsonData starcences(HttpServletRequest request) {

        cencusTask.execute();
        return Callback.success("success", "查询成功", null);
    }

}
